package ch.sv7.tool.dbmanager.db.ant;

import java.io.File;

import org.apache.tools.ant.BuildException;

import ch.sv7.tool.dbmanager.DbManagerException;
import ch.sv7.tool.dbmanager.db.DatabaseSchema;
import ch.sv7.tool.dbmanager.db.Manager;
import ch.sv7.tool.dbmanager.db.TableReader;
import ch.sv7.tool.dbmanager.db.TableWriter;
import ch.sv7.tool.dbmanager.db.sql.SQLFullTableReader;
import ch.sv7.tool.dbmanager.db.xml.StringXmlTableWriter;
import ch.sv7.tool.dbmanager.db.xml.XmlDatabaseSchemaExport;

public class BackupDatabaseTask extends TablesSqlTask {


	public void execute() throws BuildException {
		try {
			java.sql.Connection conn = getConnection();
			try {
				log("Extracting Structure informations");
				File schemaFile = new File(getDirectory(), "schema/schema.xml");
				schemaFile.getParentFile().mkdirs();
				DatabaseSchema dbSchema = getDatabaseSchema(conn, getTables());
				XmlDatabaseSchemaExport exporter = new XmlDatabaseSchemaExport();
				exporter.exportToFile(schemaFile.getAbsolutePath(), dbSchema);
				log("Structure informations saved in : " + schemaFile.getAbsolutePath());
				
				log("Extracting Data informations");
				File dataFolder = new File(getDirectory(), "data");
				dataFolder.mkdirs();
				TableReader reader = new SQLFullTableReader(conn);
				TableWriter writer = new StringXmlTableWriter(dataFolder.getAbsolutePath(), getSchema(),
						getFilePattern(), isFileZipped(), getEncoding());
				Manager.copy(reader, writer, dbSchema, dbSchema.getTableNames());
				log("Backup done!");
				
			} catch (Exception e) {
				e.printStackTrace();
				throw new BuildException(e, getLocation());
			} finally {
				closeConnection(conn);
			}
		} catch (DbManagerException e) {
			throw new BuildException(e, getLocation());
		}
	}
}
